#include "comm.h"

int destroy_msq(int msqid)
{
    if( msgctl( msqid, IPC_RMID, NULL) < 0)
    {
        perror("msgctl() error");
        return -1;
    }
    return 0;
}


int get_msqid()
{
    key_t key = ftok(PATH_NAME, PROJ_ID); // 获取key 
    if(key < 0){
        perror("ftok");
        return -1;
    }
	int msqid = msgget(key, SVMSG_MODE | IPC_CREAT);
    return msqid;
}

key_t CreateKey()
{
    int fd;
 
    if ((fd = open(PATH_NAME, O_CREAT, 0666)) < 0)
    {
        perror("open file");
        return -1;
    }
 
    close(fd);
 
    return ftok(PATH_NAME, PROJ_ID);
}

int create_msq()
{
    key_t key = CreateKey();
    if(key < 0){
        perror("ftok");
        return -1;
    }
    int msqid = msgget(key, SVMSG_MODE | IPC_CREAT );

    if(msqid < 0){
		if( errno==EEXIST )
		{
			msqid = msgget(key, SVMSG_MODE | IPC_CREAT );
		}
		else
		{
			perror("msgget");
			printf( "msgget errno code: %d\n", errno );
		    return -1;			
		}
    }
    return msqid;
}